package com.purengage.ipilih;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.purengage.ipilih.lib.Config;
import com.purengage.ipilih.lib.DBClass;
import com.purengage.ipilih.lib.DialogBox;
import com.purengage.ipilih.lib.FileHelper;
import com.purengage.ipilih.lib.HttpConnect;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class Login extends Activity {

	public class login extends AsyncTask<String, String, Boolean> {

		private ProgressDialog dialog = new ProgressDialog(Login.this);
		private String status = "";
		private String token = "";
		private String output = "";

		@Override
		protected Boolean doInBackground(String... params) {

			HttpConnect http = new HttpConnect("http://purengage.com/api/auth",
					4);
			http.addVar("client_id",
					getResources().getString(R.string.client_id));
			http.addVar("id", params[0]);
			http.addVar("pin", params[1]);
			http.addVar("indent", "1");

			boolean res = http.postData();

			if (res) {

				try {
					JSONArray re = new JSONArray("[" + http.getOutput() + "]");
					for (int i = 0; i < re.length(); i++) {
						JSONObject json = re.getJSONObject(i);

						status = json.getString("status");
						token = json.getString("token");

						String data[] = { "id", "client_id", "client_name",
								"id_prov", "id_kab", "kab_name",
								"kecamatan_id", "desa_id", "desa_name", "tps",
								"name", "mobile", "date_birth", "status",
								"date_modified", "token" };

						if (status.matches("active")) {
							for (int j = 0; j < data.length; j++) {
								DBClass db = new DBClass(Login.this);
								db.insertConf(new Config(data[j], json
										.getString(data[j])));
							}
						}
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				if (status.matches("active")) {

					String uri = "http://purengage.com/api/locations"
							+ "?client_id="
							+ getResources().getString(
									R.string.client_id) + "&token="
							+ token + "&indent=1";
					
					HttpConnect con = new HttpConnect(uri);					
					
					/* Method = GET, klo menggunakan POST pasti return failed
					 * -----------------------
					 * HttpConnect con = new
					 * HttpConnect("http://purengage.com/api/locations", 4);
					 * con.addVar("client_id",
					 * getResources().getString(R.string.client_id));
					 * con.addVar("token", token); con.addVar("indent", "1");
					 */

					boolean rs = con.getData();
					if (rs) {
						output = con.getOutput();
						Log.d("--loc--", output);
						
						FileHelper f = new FileHelper(getResources().getString(R.string.client_name));
						f.write("locations", output);
						
					}

					return true;
				} else
					return false;

			} else {
				return false;
			}

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			dialog.setMessage("Loading..");
			dialog.show();

		}

		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			dialog.dismiss();

			if (result) {
				finish();

				Intent i = new Intent();
				i.setClass(Login.this, Main.class);
				startActivity(i);
			} else {

				DialogBox popup = new DialogBox(Login.this);
				if (status.matches("failed")) {

					popup.PoupupDialog("Login Error",
							"ID dan Password tidak sesuai");

				} else if (status.matches(""))
					popup.PoupupDialog("API Error",
							"Maaf, tidak berhasil mengakses server. Silahkan ulangi lagi");

			}
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
			throws NullPointerException {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		final TextView id = (TextView) findViewById(R.id.inputUsr);
		final TextView pwd = (TextView) findViewById(R.id.inputPass);

		try {
			View.OnClickListener handler = new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					switch (v.getId()) {
					case R.id.btnLogin:

						String[] params = { id.getText().toString(),
								pwd.getText().toString() };
						new login().execute(params);

						break;
					case R.id.btnLPass:
						LupaPassword();
						break;
					default:
						break;
					}

				}
			};

			findViewById(R.id.btnLogin).setOnClickListener(handler);
			findViewById(R.id.btnLPass).setOnClickListener(handler);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	public void LupaPassword() {
		ContextThemeWrapper ctw = new ContextThemeWrapper(this,
				R.style.ThemeDialog);
		AlertDialog.Builder builder = new AlertDialog.Builder(ctw);
		LayoutInflater inflater = getLayoutInflater();
		View view = inflater.inflate(R.layout.dialog_customtitle, null);
		TextView tx = (TextView) view.findViewById(R.id.text_title);
		tx.setText("Lupa Password ?");
		String support_num = getResources().getString(
				R.string.support_phone_number);

		builder.setCustomTitle(view)
				.setMessage(
						"Silahkan hubungi koordinator survey anda di nomor berikut: "
								+ support_num)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					@TargetApi(11)
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				}).show();

	}
}
